package example;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculater extends JFrame implements ActionListener {
	JTextField jtfShow = new JTextField(40);
	JButton[] jbtNum = new JButton[10];
	JButton[] jbtOpt = new JButton[6];
	JPanel jpCenter = new JPanel();
	double temp = 0;
	int op = 4;
	private static final long serialVersionUID = 1L;

	public Calculater() {
		Container container = getContentPane();
		container.setLayout(new BorderLayout());
		jtfShow.setHorizontalAlignment(JTextField.RIGHT);
		jpCenter.setLayout(new GridLayout(4, 4));
		for (int i = 0; i < jbtNum.length; i++) {
			jbtNum[i] = new JButton("" + i);
			jbtNum[i].addActionListener(this);
			jpCenter.add(jbtNum[i]);
		}
		jbtOpt[0] = new JButton("+");
		jbtOpt[1] = new JButton("-");
		jbtOpt[2] = new JButton("*");
		jbtOpt[3] = new JButton("/");
		jbtOpt[4] = new JButton("C");
		jbtOpt[5] = new JButton("=");
		for (int i = 0; i < jbtOpt.length; i++) {
			jbtOpt[i].addActionListener(this);
			jpCenter.add(jbtOpt[i]);
		}
		container.add(jtfShow, BorderLayout.NORTH);
		container.add(jpCenter, BorderLayout.CENTER);
	}

	public static void main(String[] args) {
		Calculater frame = new Calculater();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setTitle("Calculater");
		frame.setSize(300, 300);
		frame.setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		for (int i = 0; i < jbtNum.length; i++) {
			if (e.getSource() == jbtNum[i]) {
				jtfShow.setText(jtfShow.getText() + i);
			}
		}

		for (int i = 0; i < 4; i++) {
			if (e.getSource() == jbtOpt[i]) {
				temp = Double.parseDouble(jtfShow.getText());
				op = i;
				jtfShow.setText("");
			}
		}

		if (e.getSource() == jbtOpt[4]) {
			jtfShow.setText("");
			temp = 0;
		}

		outer: if (e.getSource() == jbtOpt[5]) {
			double countResult = 0;
			switch (op) {
			case 0: {
				countResult = temp + Double.parseDouble(jtfShow.getText());
				break;
			}
			case 1: {
				countResult = temp - Double.parseDouble(jtfShow.getText());
				break;
			}
			case 2: {
				countResult = temp * Double.parseDouble(jtfShow.getText());
				break;
			}
			case 3: {
				if (Integer.parseInt(jtfShow.getText()) == 0) {
					jtfShow.setText("Error! / by zero!");
					break outer;
				}
				countResult = temp / Double.parseDouble(jtfShow.getText());
				break;
			}
			default: {
				countResult = Double.parseDouble(jtfShow.getText());
				break;
			}
			}
			op = 4;
			jtfShow.setText("" + countResult);
		}
	}
}